package com.gitee.wsl.serialization

import com.gitee.wsl.io.decodeHexToByteString
import com.gitee.wsl.io.hex
import kotlinx.io.bytestring.ByteString
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

typealias ByteStringP = @Serializable(with = ByteStringAsHexSerializer::class) ByteString?

// TODO: promote to a new okio-serializers module
object ByteStringAsHexSerializer : KSerializer<ByteString> {
    override val descriptor = PrimitiveSerialDescriptor("ByteString", PrimitiveKind.STRING)

    override fun serialize(encoder: Encoder, value: ByteString) {
        encoder.encodeString(value.hex())
    }

    override fun deserialize(decoder: Decoder): ByteString {
        return decoder.decodeString().decodeHexToByteString()
    }
}